package com.dylan.job.server;

import com.dylan.job.consts.RespCode;
import com.dylan.job.entity.RespEntity;
import com.dylan.job.utils.GsonUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

/**
 * @author dylan
 * @description 自定义业务处理器
 * @date 2025/2/12  21:15
 */
public class EmbHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final ThreadPoolExecutor bizExecutor;

    public EmbHttpServerHandler() {
        this.bizExecutor = initBizExecutor();
    }

    private ThreadPoolExecutor initBizExecutor() {
        return new ThreadPoolExecutor(
                0,
                200,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(2000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "xxl-job, EmbedServer bizThreadPool-" + r.hashCode());
                    }
                },
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        throw new RuntimeException("xxl-job, EmbedServer bizThreadPool is EXHAUSTED!");
                    }
                });
    }


    private void writeResponse(ChannelHandlerContext ctx, String json) {
        // write response
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(json, CharsetUtil.UTF_8));   //  Unpooled.wrappedBuffer(responseJson)
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");       // HttpHeaderValues.TEXT_PLAIN.toString()
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        ctx.writeAndFlush(response);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String requestData = request.content().toString(StandardCharsets.UTF_8);
        HttpMethod method = request.method();
        String url = request.uri();
        bizExecutor.execute(new Runnable() {
            @Override
            public void run() {
                //开始处理http请求
                Object result = processRequest(method, requestData, url);

                //将响应结果write出去
                writeResponse(ctx, GsonUtil.toJson(result));

            }

        });

    }

    private Object processRequest(HttpMethod method, String requestData, String url) {
        //校验方法
        if (method != HttpMethod.POST) {
            return RespEntity.error(RespCode.FAIL, "request mode error");
        }

        //找到对应的执行器执行任务


        return RespEntity.success();
    }
}
